package world;

import event.IEventHandler;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class WorldEventManager {

    private final static WorldEventManager instance = new WorldEventManager();

    public static WorldEventManager getInstance()
    {
        return instance;
    }

    private HashMap<Integer, List<IEventHandler>> events = new HashMap<>();

    private List<ByteBuffer> buffers = new ArrayList<>();

    public void sendMsg(ByteBuffer buffer)
    {
        synchronized (this) {
            buffers.add(buffer);
        }
    }

    public void addEventHandler(int type, IEventHandler handler)
    {
        if(!events.containsKey(type))
            events.put(type, new ArrayList<>());
        events.get(type).add(handler);
    }

    public void update()
    {
        synchronized (this)
        {
            buffers.forEach(buf->{
                try {
                    int type = buf.getInt();
                    List<IEventHandler> handlers = events.get(type);
                    if(handlers!=null)
                        handlers.forEach(handler->{
                            handler.handler(type, buf);
                        });
                }catch (Exception e)
                {
                    System.out.println(e);
                    throw new RuntimeException(e);
                }
            });
            buffers.clear();
        }
    }





}
